<?php
/**
 * 友情链接
 * @author 江羿平<hugcolin@163.com>
 */

use Core\AdminController;
use Models\Link;
class LinkController extends AdminController {

	protected $types = array();

	public function __construct(){
		parent::__construct();
	}

	/**
	 * 列表页
	 */
	public function index(){
		$link = new Link;
		$data['links'] = $link->order_by('sort','desc')->order_by('id','desc')->get();
		$this->load->view('admin/link/index',$data);
	}
	

	/**
	 * 添加页面
	 */
	public function add(){
		$data['back_url'] = $this->input->server('HTTP_REFERER');
		$this->load->view('admin/link/add',$data);
	}

	/**
	 * 编辑页面
	 */
	public function edit($id){
		$link = new Link;
		$data['link'] = $link->find(intval($id));
		$data['back_url'] = $this->input->server('HTTP_REFERER');
		$this->load->view('admin/link/add',$data);
	}

	/**
	 * 删除
	 */
	public function delete(){
		$link = new Link;
		$link->delete($this->input->post('id'));
		echo json_encode(array('code'=>0,'msg'=>'ok'));
	}


	/**
	 * 提交保存
	 */
	public function save(){

		$data['title'] = $this->input->post('title');
		$data['remark'] = $this->input->post('remark');
		$data['sort'] = intval($this->input->post('sort'))?intval($this->input->post('sort')):0;
		$data['url'] = $this->input->post('url');

		if(!$data['title'] || !$data['url']){
			echo json_encode(array('code'=>2,'msg'=>json_encode($data)));
			exit;
		}

		$link = new Link;
		if(intval($this->input->post('id'))){
			$link->update(intval($this->input->post('id')),$data);
			echo json_encode(array('code'=>0,'msg'=>'ok'));
		}else{
			$data['create_time'] = time();
			$link_id = $link->add($data);
			if($link_id){
				echo json_encode(array('code'=>0,'msg'=>'ok'));	
			}else{
				echo json_encode(array('code'=>1));
			}
		}
	}

}
